package jalus.dao;

import jalus.model.Comment;
import jalus.model.PMF;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class CommentDAO {
	@SuppressWarnings("unchecked")
	public List<Comment> getCommentByPost(Long postId){
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Query query = pm.newQuery(Comment.class);
	    query.setOrdering("date desc");
	    query.setFilter("postId == id");
	    query.declareParameters("Long id");
	    List<Comment> commentList;
	    try{
	    	commentList = (List<Comment>) query.execute(postId);
	    }finally{
	    	query.closeAll();
	    }
	    return commentList;
	}

	public void add(Comment comment) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			pm.makePersistent(comment);
		}finally{
			pm.close();
		}		
	}

	public Long deleteCommentById(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Comment comment = pm.getObjectById(Comment.class, id);
		Long postId = new Long(comment.getPostId());
		try{
			pm.deletePersistent(comment);
		}finally{
			pm.close();
		}
		return postId;
	}

	@SuppressWarnings("unchecked")
	public List<Comment> getCommentByRange(int start, int end) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Query query = pm.newQuery(Comment.class);
	    query.setOrdering("date desc");
	    query.setRange(start, end);
	    List<Comment> commentList;
	    try{
	    	 commentList = (List<Comment>) query.execute();
	    }finally{
	    	query.closeAll();
	    }
	    return commentList;
	}
}
